package com.yubest.tool;

import com.yubest.tool.bean.LicenseCreatorParam;
import com.yubest.tool.manage.MyLicenseManager;
import de.schlichtherle.license.*;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.security.auth.x500.X500Principal;
import java.io.*;

/**
 * License生成类
 */
@Data
@Accessors(chain = true)
public class MyLicenseCreator {

    private final static X500Principal DEFAULT_HOLDER_AND_ISSUER = new X500Principal("CN=YUBEST, OU=YUBEST, O=YUBEST, L=SZ, ST=SZ, C=CN");

    private LicenseCreatorParam creatorParam;

    public void execute() throws Exception {
        LicenseParam param = creatorParam.toLicenseParam(MyLicenseCreator.class);
        MyLicenseManager manager = new MyLicenseManager(param);
        manager.setCreator(true);
        LicenseContent content = wrapContent();
        manager.store(content, new File(creatorParam.getLicensePath()));
    }

    private LicenseContent wrapContent() {
        LicenseContent content = new LicenseContent();
        content.setHolder(DEFAULT_HOLDER_AND_ISSUER);
        content.setIssuer(DEFAULT_HOLDER_AND_ISSUER);
        content.setSubject(creatorParam.getSubject());
        content.setIssued(creatorParam.getIssuedTime());
        content.setNotBefore(creatorParam.getIssuedTime());
        content.setNotAfter(creatorParam.getExpiryTime());
        content.setConsumerType("User");
        content.setInfo("颁发给" + creatorParam.getSubject() + "的证书");
        //扩展校验服务器硬件信息
        content.setExtra(creatorParam.getDeviceInfo());
        return content;
    }

}
